import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import './common/js/permission'
//import 'nprogress/nprogress.css'
import routes from './routes'
import 'font-awesome/css/font-awesome.min.css'
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)
import axios from 'axios'
axios.defaults.baseURL='http://localhost:8080/'
Vue.prototype.$http = axios
const router = new VueRouter({
  routes
})

initIndexRouters();
function initIndexRouters(){
  if(!localStorage.menus){
    return;
  }
  //防止重复配置路由：5就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
  if(router.options.routes.length>7){
    return;
  }
  let menus = localStorage.getItem('menus');
  menus = JSON.parse(menus);
  let tempRouters = [];
  menus.forEach(menu=>{
    let indexRouter = {
      path: '/',
      iconCls: menu.icon,
      name: menu.name,
      component: resolve => require(['@/views/Home'], resolve),
      children: []
    }
    menu.children.forEach(cMenu=>{
      let cr = {
        path: cMenu.url,
        name: cMenu.name,
        component: resolve => require(['@/views/'+cMenu.component], resolve)
      }
      indexRouter.children.push(cr)
    })
    tempRouters.push(indexRouter)
    router.options.routes.push(indexRouter)
  })
  //动态路由配置
  router.addRoutes(tempRouters);
}

//为了后端校验是否已经登录，只要用axios的请求都要携带token
//=========前置拦截器=========//
axios.interceptors.request.use(config=>{
  let token = localStorage.getItem("token")
  if(token){
    config.headers["token"] = token;
  }
  return config;
},error => {
  Promise.reject(error)
})

//2 使用axios后置拦截器，处理响应的nologin错误码
axios.interceptors.response.use(result=>{
  let data = result.data;
  if (!data.success && data.message === "noLogin") {
    router.push({path: '/login'});
  }
  if (!data.success && data.message === "noPermission") {
    alert("没有权限,滚去加钱");
  }
  if (!data.success && data.message === "noTime") {
    alert("登录过期,请重新登录");
  }
  return result;
},error => {
  Promise.reject(error);
})
//静态资源拦截器
router.beforeEach((to, from, next) => {
  //如果访问的是静态资源就直接放行
  if (to.path == '/login' || to.path == 'register') {
    localStorage.removeItem('token');
    localStorage.removeItem('loginInfo');
    localStorage.removeItem('permissions');
    localStorage.removeItem('menus');
    next();
  } else {
    //如果访问的不是静态资源,就需要判断是否登录
    let loginTemp = localStorage.getItem('loginInfo');
    if (loginTemp != null) {
      next();
    } else {

      next({path: '/login'})
    }
  }
});

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

